package com.huicoo.forestmanager.widget;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.EventTypeBean;
import com.huicoo.forestmanager.others.MediaEvent;
import com.huicoo.forestmanager.ui.media.BrowseImageActivity;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.StringUtil;
import com.huicoo.forestmanager.util.audio.AudioRecordDialog;
import com.huicoo.forestmanager.util.audio.PlayAudioRecordDialog;
import com.huicoo.forestmanager.util.glide.ExploreImageLoader;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.tipsview.TipsGroupView;
import com.huicoo.forestmanager.widget.tipsview.TipsItem;
import com.liaoinstan.springview.utils.DensityUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/10	    Administrator
 * 上报问题dialog
 */
public class ReportEventDialog extends AlertDialog implements View.OnClickListener {
    private TabLayout tabLayout;
    private TipsGroupView tips_view;
    private EditText et_remark;
    private LinearLayout ll_attachment;
    private List<EventTypeBean.EventTypeData> eventTypeList;
    private List<TipsItem> tipsList;
    private String ImagePath = "";
    private String VoicePath = "";
    private String VideoPath = "";
    private String ThumbnailPath = "";
    private String reportEventUUID;

    private int voiceCount;  //音频附件累加器
    private int imgAndVideoCount; //图片和视频附件累加器。超过9个不给添加

    private OnReportEventListener onReportEventListener;

    public ReportEventDialog(Context context) {
        super(context, R.style.ActionSheetDialogStyle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_report_event_dialog);
        Window win = getWindow();
        if (win != null) {
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
        }
        setCanceledOnTouchOutside(false);
        setCancelable(true);

        init();
        EventBus.getDefault().register(this);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (EventBus.getDefault().isRegistered(ReportEventDialog.this)) {
                    EventBus.getDefault().unregister(ReportEventDialog.this);
                }
            }
        });
    }

    private void init() {
        this.reportEventUUID = CustomUtils.getUUID();

        eventTypeList = new ArrayList<>();
        tipsList = new ArrayList<>();

        TextView btn_patrol_book = findViewById(R.id.btn_patrol_book);
        TextView btn_report_event = findViewById(R.id.btn_report_event);
        ImageView btn_record = findViewById(R.id.btn_record);
        ImageView btn_camera = findViewById(R.id.btn_camera);
        btn_patrol_book.setOnClickListener(this);
        btn_report_event.setOnClickListener(this);
        btn_record.setOnClickListener(this);
        btn_camera.setOnClickListener(this);

        ll_attachment = findViewById(R.id.ll_attachment);
        et_remark = findViewById(R.id.et_remark);
        tips_view = findViewById(R.id.tips_view);
        tips_view.setIsSingleCheck(true);
        tabLayout = findViewById(R.id.tab_Layout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tipsList.clear();
                setTips(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void showPanel(List<EventTypeBean.EventTypeData> tempList) {
        show();

        if (eventTypeList == null) {
            return;
        }
        this.eventTypeList.clear();
        this.eventTypeList.addAll(tempList);

        for (int i = 0; i < eventTypeList.size(); i++) {
            EventTypeBean.EventTypeData parent = eventTypeList.get(i);
            tabLayout.addTab(tabLayout.newTab().setText(parent.Name), i == 0);
        }
        //初始显示第0个父分类的子分类
        tipsList.clear();
        setTips(0);

        Window win = getWindow();
        if (win != null) {
            win.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }
    }

    private void setTips(int parentPosition) {
        if (eventTypeList.isEmpty()) {
            return;
        }
        tips_view.removeAllViews();
        EventTypeBean.EventTypeData parent = eventTypeList.get(parentPosition);
        if (parent.Child != null) {
            for (EventTypeBean.EventTypeData child : parent.Child) {
                TipsItem item = new TipsItem();
                item.tipId = child.ID;
                item.tipName = child.Name;
                tipsList.add(item);
            }
            tips_view.initViews(tipsList, null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_patrol_book: {
                HashMap<String, String> params = createParams(1);
                if (params != null && onReportEventListener != null) {
                    onReportEventListener.reportEvent(params);
                }
                break;
            }
            case R.id.btn_report_event: {
                HashMap<String, String> params = createParams(2);
                if (params != null && onReportEventListener != null) {
                    onReportEventListener.reportEvent(params);
                }
                break;
            }
            case R.id.btn_record:
                recordVoice();
                break;
            case R.id.btn_camera:
                if (imgAndVideoCount >= 9) {
                    ToastUtils.show("图片和视频附件数量已达上限");
                    return;
                }
                camera();
                break;
            default:
                break;
        }
    }

    private void recordVoice() {
        AudioRecordDialog dialog = new AudioRecordDialog(getContext());
        dialog.setMaxSeconds(60);
        dialog.setOnAudioRecordCompleteListener(new AudioRecordDialog.OnAudioRecordCompleteListener() {
            @Override
            public void recordComplete(String filePath, int during) {
                HashMap<String, String> params = new HashMap<>();
                params.put("Token", CustomUtils.getToken());
                params.put("IsCheckRepeat", "1");
                params.put("UID", CustomUtils.getUUID());
                AttachmentEntity attachmentEntity = new AttachmentEntity(1, AttachmentHelper.getFileName(filePath), new File(filePath), during);
                if (onReportEventListener != null) {
                    onReportEventListener.uploadFile(params, attachmentEntity, reportEventUUID);
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void playVoice(String filePath) {
        PlayAudioRecordDialog dialog = new PlayAudioRecordDialog(getContext());
        dialog.showDialog(filePath, new PlayAudioRecordDialog.OnPlayVoiceErrorListener() {
            @Override
            public void onError() {
                ToastUtils.show("录音播放异常，请重试");
            }
        });
    }

    private void camera() {
        CameraSelectionDialog dialog = new CameraSelectionDialog(getContext());
        dialog.show();
    }

    private ImageView createImageAttachmentItem() {
        ImageView imageView = new ImageView(getContext());
        // 图片附件宽度90，其他附件宽度60
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        imageView.setLayoutParams(layoutParams);
        return imageView;
    }

    private View createVoiceAttachmentItem(int during) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_add_media_attachment, null);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_desc = view.findViewById(R.id.tv_desc);
        voiceCount++;
        tv_title.setText("录音" + voiceCount);
        tv_desc.setText(during + "''");
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        view.setLayoutParams(layoutParams);
        return view;
    }

    private View createVideoAttachmentItem(String thumb) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_add_video_attachment, null);
        ImageView iv_thumb = view.findViewById(R.id.iv_thumb);
        if (!TextUtils.isEmpty(thumb)) {
            ExploreImageLoader.getInstance().loadImage(getContext(), thumb, iv_thumb);
        } else {
            iv_thumb.setImageResource(R.drawable.icon_video);
        }
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        view.setLayoutParams(layoutParams);
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void captureMediaSuccessEvent(MediaEvent event) {
        LogUtils.v("gogogo on success event = " + event.type + " -- " + event.filePath);
        String filePath = event.filePath;
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        params.put("IsCheckRepeat", "1");
        params.put("UID", CustomUtils.getUUID());
        AttachmentEntity attachmentEntity = new AttachmentEntity(event.type, AttachmentHelper.getFileName(filePath), new File(filePath), event.during);
        if (onReportEventListener != null) {
            onReportEventListener.uploadFile(params, attachmentEntity, reportEventUUID);
        }
    }

    // 播放视频
    private void playVideo(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Context context = getContext();
        Dialog dialog = new Dialog(context, R.style.PlayVideoDialog);
        dialog.setCanceledOnTouchOutside(false);
        //创建video view
        RelativeLayout relativeLayout = new RelativeLayout(context);
        VideoView mVideoView = new VideoView(context);
        mVideoView.setVideoPath(path);
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.v("gogogo play video fail");
                dialog.dismiss();
                boolean isDelete = AttachmentHelper.deleteFile(path);
                LogUtils.v("gogogo delete file = " + isDelete);
                ToastUtils.show("视频播放异常，请重试");
                return false;
            }
        });
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        relativeLayout.addView(mVideoView, layoutParams);
        //dialog添加view
        ViewGroup.LayoutParams rootLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(relativeLayout, rootLayoutParams);
        Window mWindow = dialog.getWindow();
        if (mWindow != null) {
            WindowManager.LayoutParams lp = mWindow.getAttributes();
            int mScreenWidth = DisplayUtil.getScreenWidth(context);
            int mScreenHeight = DisplayUtil.getScreenHeight(context);
            lp.width = mScreenWidth; // 宽度
            lp.height = (int) (mScreenHeight * 0.6); // 高度
            mWindow.setAttributes(lp);
        }
        dialog.show();
        mVideoView.start();
    }

    public interface OnReportEventListener {
        void uploadFile(HashMap<String, String> params, AttachmentEntity attachmentEntity, String relateEventUID);

        void reportEvent(HashMap<String, String> params);

        void reportEventOpenVideo(int type, String path);
    }

    public void setOnReportEventListener(OnReportEventListener onReportEventListener) {
        this.onReportEventListener = onReportEventListener;
    }

    private HashMap<String, String> createParams(int reportType) {
        String eventTypeId = "";
        String description = "";

        boolean isSelectType = false;
        for (TipsItem item : tipsList) {
            if (item.isChecked) {
                isSelectType = true;
                eventTypeId = item.tipId;
            }
        }
        if (!isSelectType) {
            ToastUtils.show("请选择事件类型");
            return null;
        }

        description = et_remark.getText().toString().trim();
        if (imgAndVideoCount <= 0) {
            ToastUtils.show("至少添加一个图片或视频");
            return null;
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("ReportingType", String.valueOf(reportType));
        params.put("EventTypeID", eventTypeId);
        params.put("Description", description);
        params.put("ImagePath", ImagePath);
        params.put("VoicePath", VoicePath);
        params.put("VideoPath", VideoPath);
        params.put("ThumbnailPath", ThumbnailPath);
        params.put("IsCheckRepeat", "1");
        params.put("UID", reportEventUUID);
        return params;
    }

    // 附件
    public void addFilePath(int attachmentType, String fileName, String ThumbnailFile, int during) {
        LogUtils.v("gogogo attachment = " + attachmentType + "  --  " + fileName);
        if (attachmentType == 1) {
            View itemView = createVoiceAttachmentItem(during);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVoice(fileName);
                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(VoicePath)) {
                VoicePath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                VoicePath += "|";
                VoicePath += StringUtil.getUrlParam(fileName, "filename");
            }
        } else if (attachmentType == 2) {
            ImageView itemView = createImageAttachmentItem();
            ExploreImageLoader.getInstance().loadImage(getContext(), fileName, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("imgUrl", fileName);
                    Intent intent = new Intent(getContext(), BrowseImageActivity.class);
                    intent.putExtras(bundle);
                    getContext().startActivity(intent);

                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(ImagePath)) {
                ImagePath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                ImagePath += "|";
                ImagePath += StringUtil.getUrlParam(fileName, "filename");
            }
            //图片和视频累加器
            imgAndVideoCount++;
        } else if (attachmentType == 3) {
            View itemView = createVideoAttachmentItem(ThumbnailFile);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVideo(fileName);
                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(VideoPath)) {
                VideoPath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                VideoPath += "|";
                VideoPath += StringUtil.getUrlParam(fileName, "filename");
            }
            if (TextUtils.isEmpty(ThumbnailPath)) {
                ThumbnailPath = StringUtil.getUrlParam(ThumbnailFile, "filename");
            } else {
                ThumbnailPath += "|";
                ThumbnailPath += StringUtil.getUrlParam(ThumbnailFile, "filename");
            }
            //图片和视频累加器
            imgAndVideoCount++;
        }
    }
}
